<template>
    <div class="user">
        <el-row>
            <el-col :span="24">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item :to="{ path: '/user' }">用户列表</el-breadcrumb-item>
                    <el-breadcrumb-item>添加用户</el-breadcrumb-item>
                </el-breadcrumb>
            </el-col>
        </el-row>
        <!-- 搜索框 -->
        <el-row>
            <el-col :span="24">
                <el-input placeholder="请输入内容" class="search-input" v-model="query" @keydown.native.enter="initList">
                <el-button slot="append" icon="el-icon-search" @click="initList"></el-button>
                </el-input>
                <el-button type="success" plain @click="addDialogFormVisible = true">添加用户</el-button>
            </el-col>
        </el-row>
        <!-- 用户数据列表 -->
        <el-table
            v-loading="loading"
            class="margin20"
            :data="userList"
            border
            style="width: 100%">
            <el-table-column
            type="index">
            </el-table-column>
            <el-table-column
            prop="username"
            label="姓名"
            width="180">
            </el-table-column>
            <el-table-column
            prop="email"
            label="邮箱"
            width="180">
            </el-table-column>
            <el-table-column
            prop="mobile"
            label="电话">
            </el-table-column>
            <el-table-column label="用户状态" width="180">
                <template slot-scope="scope">
                    <el-switch
                    v-model="scope.row.mg_state"
                    active-color="#13ce66"
                    @change="changeUserState(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope" width="180">
                    <el-button type="primary" plain size="mini" icon="el-icon-edit" @click="showEdit(scope.row)"></el-button>
                    <el-button type="danger" plain size="mini"  icon="el-icon-delete" @click="showDelete(scope.row)"></el-button>
                    <el-button type="warning" plain size="mini" icon="el-icon-check" @click="showGrantRole(scope.row)"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="page">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagenum"
            :page-sizes="[1, 2, 3, 4]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </div>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
            <el-form :model="addForm" :label-width="formLabelWidth" :rules="rules" ref="addForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUserSubmit('addForm')">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 编辑用户对话框 -->
        <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
            <el-form :model="editForm" :label-width="formLabelWidth" :rules="rules" ref="editForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" auto-complete="off" :disabled='true'></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserSubmit('editForm')">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 分配用户角色对话框 -->
        <el-dialog title="分配用户角色" :visible.sync="grantRoleDialogFormVisible">
            <el-form :model="grantRoleForm" :label-width="formLabelWidth">
                <el-form-item label="用户名:">
                    <el-tag type="info">{{grantRoleForm.username}}</el-tag>
                </el-form-item>
                <el-form-item label="请选择角色：">
                    <el-select v-model="roleId" placeholder="请选择角色">
                    <el-option v-for="(value,index) in roleList" :key="index" :label="value.roleName" :value="value.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="grantRoleDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="grantRoleSubmit">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
import {getUserList,setUserState,addUser,getUserById,editUser,deleteUser,getRolesList,grantUserRole} from "@/api"
export default {
    data() {
        return {
                loading:true,
                pagenum:1,
                pagesize:3,
                total:0,
                query:"",
                userList: [],
                formLabelWidth:'120px',
                addDialogFormVisible:false,
                addForm:{
                    username:'',
                    password:"",
                    email:"",
                    mobile:""
                },
                rules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }
                    ],
                    mobile: [
                        { required: true, message: '电话不能为空' }
                    ]
                },
                editDialogFormVisible:false,
                editForm:{
                    username:'',
                    email:"",
                    mobile:"",
                    id:0
                },
                grantRoleDialogFormVisible: false,
                grantRoleForm:{},
                roleList:[],
                roleId:""
        }
    },
    mounted(){
        this.initList()
    },
    methods: {
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`)
            this.pagesize = val
            this.initList()
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`)
            this.pagenum = val
            this.initList()
        },
        //初始化表格数据
        initList(){
            this.loading = true
            let params = {params:{query:this.query,pagenum:this.pagenum,pagesize:this.pagesize}}
            getUserList(params).then(res=>{
                console.log(res);
                if(res.meta.status === 200){
                    this.userList = res.data.users
                    this.total = res.data.total
                    this.loading = false
                }
                
            })
        },
        //更改用户状态
        changeUserState(row) {
            console.log(row);
            setUserState({uId:row.id,type:row.mg_state}).then(res => {
               console.log(res);
               if(res.meta.status === 200){
                    this.$message({
                        message: '更改用户状态成功',
                        type: 'success'
                    });
               }else{
                   this.$message({
                        message: res.meta.msg,
                        type: 'warning'
                    });
               }
            })
        },
        //添加用户
        addUserSubmit(formName){
            this.$refs[formName].validate(valid => {
                if(valid){
                    addUser(this.addForm).then(res => {
                        console.log(res);
                        if(res.meta.status === 201){
                            this.$message({
                                message: '添加用户成功',
                                type: 'success'
                            });
                        }
                        this.addDialogFormVisible = false
                        this.initList()
                    })
                }
            })
        },
        //展示编辑用户对话框
        showEdit(row){
            this.editDialogFormVisible = true
            console.log(row);
            getUserById(row.id).then(res => {
                console.log(res);
                if(res.meta.status = 200){
                    this.editForm.username = res.data.username
                    this.editForm.email = res.data.email
                    this.editForm.mobile = res.data.mobile
                    this.editForm.id = res.data.id
                }
            })
        },
        //编辑提交
        editUserSubmit(formName){
            this.$refs[formName].validate(valid => {
                if(valid) {
                    editUser(this.editForm).then(res => {
                        console.log(res);
                        if(res.meta.status === 200){
                            this.$message({
                                message: '编辑用户成功',
                                type: 'success'
                            });
                            this.editDialogFormVisible = false
                            this.initList()
                        }
                    })
                }
            })
        },
        //删除用户
        showDelete(row){
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {
                    // 执行删除用户操作
                    deleteUser(row.id).then(res => {
                        console.log(res);
                        if(res.meta.status === 200){
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.initList()
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
            });
        },
        //显示分配角色对话框
        showGrantRole(row){
            this.grantRoleDialogFormVisible = true
            this.grantRoleForm = row
            getRolesList().then(res => {
                console.log(res);
                if(res.meta.status === 200) {
                    this.roleList = res.data
                } 
            })
        },
        //分配用户角色
        grantRoleSubmit(){
            if(!this.roleId) {
                this.$message({
                    message: '角色名不能为空，请选择用户角色',
                    type: 'warning'
                });
            }else {
                grantUserRole({id:this.grantRoleForm.id,rid:this.roleId}).then(res => {
                    console.log(res);
                    if(res.meta.status === 200){
                        this.$message({
                            message: '编辑用户成功',
                            type: 'success'
                        });
                        this.grantRoleDialogFormVisible = false
                    }else{
                        this.$message({
                            message: res.meta.msg,
                            type: 'error'
                        });
                    }
                })
            }
            
        }
        
    }
}
</script>
<style lang="scss" scoped>
    .user {
        .margin20 {
            margin: 20px 0;
        }
        .search-input {
            width: 300px;
        }
        .page {
            padding: 5px 0;
            background-color: #D3DCE6;
        }
    }
</style>
